/**
 * Created by yxt on 2015/5/8.
 */

(function ($) {
    var me = {};
    var Menu = function(element, options) {
        this.element = $(element);
        if(options != undefined && options != null && options.ajaxOption != undefined  && options.ajaxOption != null){
            $.extend(this.ajaxOption,options.ajaxOption);
        }
        delete options.ajaxOption;
        $.extend(this,options);
        me = this;
    };
    /**
     * 导航数据键值对存储
     */
    function menuToMap(menuList){
        if(menuList == null || menuList == "" || menuList == {} || menuList.length == 0) return;
        $.each(menuList,function(i,val){
            me.menuMap.put(val.id,val);
            menuToMap(val.children);
        });
    }
    /**
     * 默认配置
     */
    Menu.prototype = {
        constructor: Menu,
        /**
         * 是否自动加载
         */
        autoLoad: true,
        /**
         * 异步请求参数
         */
        ajaxOption:{
            type: "get",//使用get方法访问后台
            dataType: "json",//返回json格式的数据
            url: app.contextPath + "/app/data/menu.json",//要访问的后台地址
            async: false,
            success:function(data){
                me.loadSuccess(arguments);
                me.menuData = data.message;
                me.menuMap = new HashMap();
                menuToMap(me.menuData);
            },
            error:function(data){
                me.loadError(arguments);
            }
        },
        /**
         * 设置导航div元素
         */
        menuElement:{
            parentTemplate:'<li class="" id="{0}">' + 
                        '<a href="#" class="dropdown-toggle">' + 
                            '<i class="menu-icon fa {1}"></i>' + 
                            '<span class="menu-text"> {2} {4}</span>' + 
                            '<b class="arrow fa fa-angle-down"></b>' + 
                        '</a>',
            menuTemplate :'<li class="" id="{0}">' + 
                        '<a data-url="page/{3}" href="#page/{3}">' + 
                            '<i class="menu-icon fa {1}"></i>' + 
                            '<span class="menu-text"> {2} {4}</span>' + 
                        '</a>' + 
                        '<b class="arrow"></b>' + 
                    '</li>'
        },
        /**
         * 设置标题
         */
        setTitle:function(title){
            this.title = title;
            return this;
        },
        /**
         * 获取标题
         */
        getTitle:function(){
            return this.title;
        },
        /**
         * 加载数据
         * @param data 传入的数据 如果传入了数据，则不进行 ajax 数据加载
         */
        load:function(data){
           if(me.menuData != null && me.menuData != undefined){
                return;
            }
            if(typeof data === "Object"){
                me.menuData = data;
            }else{
                me.beforeLoad();
                $.ajax(me.ajaxOption);
                me.afterLoad();
                me.show();
            }
            me.createEle();
        },
        /**
         * 加载数据前操作
         */
        beforeLoad:function(){},
        /**
         * 加载数据之后操作
         */
        afterLoad:function(){},
        /**
         * 数据加载成功
         */
        loadSuccess:function(args){},
        /**
         * 数据加载失败
         */
        loadError:function(args){},
        /**
         * 创建菜单的 Element
         */
        createEle:function(args){
			var data = this.menuData;
			var hash = window.location.hash, hashArr = hash.split('?');
			me.element.find("li a").each(function() {
				var href = $(this).attr("href");
				if( href == hashArr[0] ) {
					$(this).parents("ul").parent("li").addClass("active open");
					$(this).parent("li").addClass("active");
				}
			});
        },
        /**
         * 显示导航之后操作
         */
        afterShow:function(){},
        /**
         * 显示导航之前操作
         */
        beforShow:function(){},
        /**
         * 显示导航
         */
        show:function(){
            var apendMenuHtml = function(data){
                var menuHtml = "";
                $.each(data, function(i,val){
                    var _id = val.id || "", _icon = val.icon || "", _menuName = val.menuName || "", _url = val.url || "", _tooltip = val.tooltip || "";
                    if(val.children == null || val.children.length == 0){
                        menuHtml += me.menuElement.menuTemplate.format(_id,_icon,_menuName,_url,_tooltip);
                    }else{
                        menuHtml += me.menuElement.parentTemplate.format(_id,_icon,_menuName,_url,_tooltip);
                        menuHtml += '<ul class="submenu">';
                        menuHtml += apendMenuHtml(val.children);
                        menuHtml += '</ul></li>';
                    }
                });
                return menuHtml;
            };
            var html = apendMenuHtml(me.menuData);
            me.element.html(html);
        },
        /**
         * 设置激活
         * @param menuNode 菜单Id或菜单的Node
         */
        setActive:function(menuNode) {},
        /**
         * 激活之后操作
         * @param menuNode 菜单Id或菜单的Node
         */
        afterActive:function(menuNode){},
        /**
         * 打开菜单
         * @param menuNode
         */
        openMenu:function(menuNode){}
    };
    /**
     * 扩展 Jquery 对象为 Menu
     * @param option
     */
    $.fn.menu = function(option){
        return this.each(function () {
            var $this = $(this),
                data = $this.data('menu'),
                options = typeof option === 'object' && option;
            if (!data)  {
                $this.data('menu', (data = new Menu(this, $.extend({}, options))));
            }
            if (typeof option == 'string') {
                data[option]();
            }
            if(data.autoLoad){
                data.load(options.data);
            }
        });
    };
    /**
     * 属性返回对创建此对象的函数的引用
     */
    $.fn.menu.Constructor = Menu;

})(jQuery);


